<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, inject, Ref, onBeforeUnmount } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { Row } from '@/api/franchiser'
const { required } = useValidator()
const currentRow: Ref<Row> = inject('currentRow') as Ref<Row>

const { formRegister, formMethods } = useForm()

const { setValues, getFormData, getElFormExpose } = formMethods

const schema = reactive<FormSchema[]>([
  {
    field: 'mobile',
    label: '登录账号',
    component: 'Input',
    formItemProps: {
      rules: [
        required(),
        { min: 11, max: 11, message: '请输入登录账号', trigger: 'blur' },
        {
          pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
          message: '请输入登录账号',
          trigger: 'blur'
        }
      ]
    },
    componentProps: {
      placeholder: '请输入登录账号'
    }
  },
  {
    field: 'password',
    label: '设置密码',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 6, max: 15, message: '输入6-15个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '输入6-15个字符'
    }
  },
  {
    field: 'user_name',
    label: '账号名称',
    component: 'Input',
    formItemProps: {
      rules: [
        required(),
        { min: 6, max: 20, message: '请输入至少6字符最多支持20字符', trigger: 'blur' }
      ]
    },
    componentProps: {
      placeholder: '输入6-20个字符'
    }
  }
  // {
  //   field: 'real_name',
  //   label: '选择角色',
  //   component: 'Input',
  //   formItemProps: {
  //     rules: [required()]
  //   }
  // }
])

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const formDataList = {
      id: formData.id,
      real_name: formData.real_name,
      password: formData.password,
      mobile: formData.mobile,
      user_name: formData.user_name
    }
    return formDataList
  }
}

const reset = async () => {
  const elForm = await getElFormExpose()
  elForm?.resetFields()
}

watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

onBeforeUnmount(reset)

defineExpose({
  submit,
  reset
})
</script>

<template>
  <Form @register="formRegister" :schema="schema" />
</template>
